import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { Toaster } from 'sonner';
import App from "./App.tsx";
import "./index.css";
import { AuthContext } from './contexts/authContext';
import { useState, useEffect, ReactNode } from 'react';

const AuthProvider = ({ children }: { children: ReactNode }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState<any>(null);
  const [token, setToken] = useState<string | null>(null);


  useEffect(() => {
    // 从localStorage加载用户认证状态和token
    const savedUser = localStorage.getItem('user');
    const savedToken = localStorage.getItem('token');
    
    if (savedUser && savedToken) {
      try {
        const parsedUser = JSON.parse(savedUser);
        setIsAuthenticated(true);
        setUser(parsedUser);
        setToken(savedToken);
      } catch (error) {
        console.error('Failed to parse user data from localStorage', error);
        // 清除无效的用户数据
        localStorage.removeItem('user');
        localStorage.removeItem('token');
      }
    }
  }, []);

  const setAuth = (value: boolean, userData?: any, token?: string) => {
    setIsAuthenticated(value);
    if (userData && token) {
      setUser(userData);
      localStorage.setItem('user', JSON.stringify(userData));
      localStorage.setItem('token', token);
    } else {
      setUser(null);
      setToken(null);
      localStorage.removeItem('user');
      localStorage.removeItem('token');
    }
  };

  const logout = () => {
    setAuth(false);
  };

  return (
    <AuthContext.Provider value={{ isAuthenticated, user, token, setIsAuthenticated: setAuth, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <BrowserRouter>
      <AuthProvider>
        <App />
        <Toaster />
      </AuthProvider>
    </BrowserRouter>
  </StrictMode>
);